import React, { PureComponent } from "react";
// import { connect } from 'dva';
import style from "styled-components";
import {
  // Input,
  Button,
  Form,
  TreeSelect,
  // DatePicker,
  // InputNumber,
  Radio,
  // Icon,
  // Checkbox,
  Tree,
  message
} from "antd";
import Drawer from "react-motion-drawer";
import bcx_utils from "../../../common/bcx_utils";
// import PSelect from "../../../components/Pro/PSelect";
// import * as api from "../../../services/api";

import {
  //searchRoleAndRoleGroupList,//查询角色组与角色列表功能
  //enterpriseRoleSave,//角色新增
  getDictInformation, //字典数据
  getTreeDepart, //选择部门
  systemSysMenuAllMenuTree, //获取所有菜单--树形
  systemComRoleAllotSave, //角色权限新增修改
  systemComRoleAllotGet //GET获取角色权限
} from "../../../services/api";

// const FormItem = Form.Item;
// const { Option } = Select;
const { TreeNode } = Tree;
const RadioboxGroup = Radio.Group;

message.config({
  top: 100,
  right: 5,
  duration: 2
});

// @connect(state => ({ profile: state.profile }))
@Form.create()

// 角色权限抽屉
export default class RoleAllow extends PureComponent {
  constructor(props, context) {
    super(props, context);
    this.state = {
      roleId: this.props.roleId,
      roleName: this.props.caption,
      open: this.props.visiable, //备注
      departData: "", //特定部门
      departName: "", //特定部门名称
      dataAuthType: [], //权限管理范围
      //权限分配树组件
      checkedKeys: [], //选中的功能权限
      permissionsTree: [], //部门树
      radioValue: "" //默认初始化
    };
  }
  /******************************生命周期******************************/

  componentDidMount() {
    this.getAllType(); //获取所有类型-页面需要的数据字典
    this.getTreeDepart();
    this.systemSysMenuAllMenuTree(); //树
  }
  componentWillReceiveProps(props) {
    if (this.state.roleId !== props.roleId) {
      this.systemComRoleAllotGet(props.roleId);
    }
    this.setState({
      open: props.visiable,
      roleId: props.roleId,
      roleName: props.caption
    });
  }
  /******************************ajax请求******************************/

  /******************************相关事件******************************/

  //权限分配树形组件
  // onExpand = (expandedKeys) => {
  //   console.log('onExpand', arguments);
  //   // if not set autoExpandParent to false, if children expanded, parent can not collapse.
  //   // or, you can remove all expanded children keys.
  //   this.setState({
  //     expandedKeys,
  //     autoExpandParent: false,
  //   });
  // }

  //选中节点后
  getTreeDepart = () => {
    getTreeDepart({}).then(
      ({ data = [] }) => {
        console.log(data, "getTreeDepart-选择部门-data");
        this.setState({ departTree: data });
      },
      err => {
        console.log(err, "getTreeDepart-选择部门-err");
      }
    );
  };

  //获得公共信息
  getAllType = () => {
    getDictInformation({ codeTypes: "dataAuthType" }).then(res => {
      console.log("角色权限-权限设置管理范围字典-res:", res);
      //判断获取数据是否为空
      if (res.data) {
        const allTypeData = res.data;
        this.setState({
          dataAuthType: allTypeData.dataAuthType //权限管理范围
        });
      }
    });
  };

  //权限选中
  onPermCheck = checkedKeys => {
    this.setState({ checkedKeys });
  };

  //获取所有菜单--树形
  systemSysMenuAllMenuTree = () => {
    systemSysMenuAllMenuTree({}).then(
      ({ data: [permissionsTree] }) => {
        let newArr1 = [{ ...permissionsTree, ...{ title: "全部权限" } }];
        //迭代自身，
        const deleteChild = arr => {
          const newArr = JSON.parse(JSON.stringify(arr));
          newArr.forEach(({ title, key, children }, index) => {
            newArr[index] = {
              title,
              key,
              children
            };
            if (newArr[index].children.length !== 0) {
              newArr[index].children = deleteChild(children);
            } else {
              delete newArr[index].children;
            }
          });
          return newArr;
        };
        newArr1 = deleteChild(newArr1);
        this.setState({ permissionsTree: newArr1 });
      },
      err => {
        console.log(err);
      }
    );
  };

  //获取角色权限
  systemComRoleAllotGet = roleId => {
    // this.setState({ loading: true })
    console.log("获取角色权限-当前角色ID", this.state.roleId);
    systemComRoleAllotGet({ roleId }).then(
      ({ data: { dataAuthType, departId, menuIds } }) => {
        // (data) => {
        // console.log("拉取所有权限值值值！！！！！！！", data);
        this.setState({
          radioValue: dataAuthType,
          checkedKeys: menuIds.split(",")
        });
        if (dataAuthType === "4") {
          this.setState({ departData: departId.toString() }, () => {
            console.log(this.state.departData);
          });
        }
      },
      err => {
        console.log(err);
        // this.setState({ loading: true })
      }
    );
  };

  //表单提交-保存
  handleSaveRoleAllowSubmit = () => {
    const { roleId, radioValue, departData, checkedKeys } = this.state;

    //选择"特定部门"
    let departId = "";
    if (radioValue === "4") {
      departId = departData;
    }
    //移除全选时候 组件自动添加的属性。
    if (checkedKeys.includes("0-0")) {
      checkedKeys.pop();
    }
    const obj = {
      roleId,
      dataAuthType: radioValue,
      departId,
      menuIds: checkedKeys.join()
    };
    this.systemComRoleAllotSave(obj);
  };

  //角色权限新增修改-保存
  systemComRoleAllotSave = ajaxData => {
    const { dataAuthType, menuIds } = ajaxData;
    bcx_utils.preventRepeatAsync(callback =>
      callback(resolve => {
        if (dataAuthType === "") {
          message.error("请选择管理范围", 1.5, () => {
            resolve();
          });
        } else if (menuIds.length === 0) {
          message.error("请选择功能权限", 1.5, () => {
            resolve();
          });
        } else {
          //角色权限新增修改
          systemComRoleAllotSave(ajaxData).then(
            data => {
              console.log(data);
              message.success(data.msg);
              resolve();
              this.setState({ open: false });
              this.props.refreshList();
            },
            err => {
              console.log(err);
              message.error(err.msg);
            }
          );
        }
      })
    );
  };

  //管理范围
  onRadioChange = e => {
    this.setState({ radioValue: e.target.value });
  };
  //管理范围 特定部门选中
  onPartChange = (value, label) => {
    this.setState({ departData: value, departName: label }, () => {
      console.log("特定部门名称", this.state.departName);
    });
  };

  /******************************render******************************/
  //权限分配树形组件
  renderTreeNodes = data => {
    return data.map(item => {
      if (item.children) {
        return (
          <TreeNode title={item.title} key={item.key} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode {...item} dataRef={item} />;
    });
  };

  //权限管理范围
  renderDataAuthType = () => {
    return this.state.dataAuthType.map((val, key) => {
      return (
        <div key={key} style={{ marginBottom: 18 }}>
          <Radio key={key} value={val.codeValue + ""}>
            {val.label}
          </Radio>
        </div>
      );
    });
  };

  render() {
    return (
      <Box>
        <Drawer
          overlayColor="rgba(0, 0, 0,0)"
          right
          open={this.state.open}
          noTouchClose
          width={600}
          zIndex={999}
          className="drawer-box permissions-allocation"
          onChange={open => {
            this.props.onChange(open);
            this.setState({ open });
          }}
        >
          <div className="drawer">
            <div className="drawer-header">
              {this.state.roleName}（权限分配）
            </div>
            <div className="drawer-content">
              <div className="permissions-form">
                {/* 测试（权限分配） */}
                <div className="permissions-top">
                  <div className="item">
                    <div className="l ant-form-item-required">管理范围:</div>
                    <div className="c">
                      <RadioboxGroup
                        onChange={this.onRadioChange}
                        value={this.state.radioValue}
                      >
                        {this.renderDataAuthType()}
                      </RadioboxGroup>
                      {this.state.radioValue === "4" && (
                        <div>
                          <TreeSelect
                            dropdownStyle={{ maxHeight: 400, overflow: "auto" }}
                            style={{ width: 294, margin: "0 0 24px 20px" }}
                            placeholder="请选择特定企业部门"
                            treeData={this.state.departTree}
                            value={this.state.departData}
                            treeDefaultExpandAll
                            onChange={this.onPartChange}
                          />
                        </div>
                      )}
                    </div>
                  </div>
                </div>
                <div className="permissions-bottom">
                  <div className="item">
                    <div className="l ant-form-item-required">功能权限:</div>
                    <div className="c perm permissions-tree">
                      <Tree
                        checkable
                        onCheck={this.onPermCheck}
                        checkedKeys={this.state.checkedKeys}
                        className="permissions-tree"
                      >
                        {this.renderTreeNodes(this.state.permissionsTree)}
                      </Tree>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div className="drawer-footer">
              <Button onClick={() => this.setState({ open: false })}>
                取消
              </Button>
              <Button
                onClick={this.handleSaveRoleAllowSubmit}
                type="primary"
                style={{ marginLeft: 8 }}
                htmlType="submit"
              >
                保存
              </Button>
            </div>
          </div>
        </Drawer>
      </Box>
    );
  }
}

/************************样式************************/

const Box = style.div`{
  .item{
    .l{
       font-size: 14px;
       color: #666666;
       width:84px;
       display:inline-block;
       float:left
    }
    .c{
      margin-left:84px;
      vertical-align: top;
      &.perm{
       position: relative;
       top: -7px;
      }
    }
  }
  .drawer-content{
    margin-top:28px;
  }
}`;
